<template>
	<view class="">
		<view class="spliceLine">
		</view>
		<view class="writeInfo-contaienr">
			<view class="wreteInfo-body">
				<input type="text" v-model="publishForm.title" class="wreteInfo" placeholder="项目名称">
			</view>
			<!-- 写一个项目简介 -->
			<!-- <view class="writeIntro-body">
				<textarea v-model="publishForm.content" placeholder="项目简介" class="writeIntro"
					:style="{ 'height': '150px', 'overflow-y': 'hidden' }"></textarea>
			</view> -->
			<view class="writeDetail-body">
				<!-- <textarea v-model="detail" placeholder="项目详情" class="writeDetail"
					:style="{ 'height': '150px', 'overflow-y': 'hidden'}"></textarea> -->
				<view class="richtext">
					<!-- @changes="saveContens" -->
					<piaoyiEditor :values="values" :maxlength="3000" @changes="saveContens" :readOnly="readOnly"
						:photoUrl="photoUrl" :api="api" :name="name" autofocus ref="editor" />
					<Attachment mode="create" :canUploadFile="true" :uploadFileUrl="uploadUrl" :isEdit="true"
						@uploadSuccess="uploadSuccess" :header="header" :showProcess="true"
						:attachmentList.sync="attachmentList"></Attachment>
				</view>
			</view>
			<view class="wreteInfo-body">
				<input type="text" v-model="keywordsInput" class="wreteInfo" placeholder="请填写项目关键字以“,”分隔">
			</view>
			<!-- <view class="price">
				<view class="price-title">
					<text>设为热门</text>
				</view>
				<view class="price-body">
					<switch @change="SwitchA" :class="switchA?'checked':''" :checked="switchA?true:false"></switch>
				</view>
			</view> -->
			<view class="price">
				<view class="price-title">
					<text>你的城市</text>
				</view>
				<view class="price-body">
					<input type="text" v-model="publishForm.city" class="price-input" placeholder="城市">
				</view>
			</view>

			<view class="price">
				<view class="price-title">
					<text>项目预算</text>
				</view>
				<view class="price-body">
					<input type="number" v-model="publishForm.price" class="price-input" placeholder="项目预算（元）">
				</view>
			</view>

			<!-- 底部发布按钮 -->
			<view class="publish-btn">
				<button @tap="publishBtn" ref="formButton" class="cu-btn round bg-blue xl"
					style="width:200px;height:70px;font-size:46rpx">立即修改</button>
			</view>
		</view>
	</view>
</template>

<script>
	import piaoyiEditor from '@/uni_modules/piaoyi-editor/components/piaoyi-editor/piaoyi-editor.vue';
	import Attachment from '../../components/jin-attachment/jin-attachment.vue';

	export default {
		data() {
			return {
				domainPrefix:'',
				ImagesList: '',
				filesList: '',
				switchA: false,
				attachmentList: [
					// {
					// 	url: '"http://tmp/veD7erARb1vC7938720343ad7afc3cb256263972c60c.docx"',
					// 	type: 'file',
					// 	fileName: 'xxx.png'
					// },
				],
				attachmentList2:[],
				header: {
					'token': ''
				},
				uploadUrl: this.domainPrefix + this.$myHttp.urlMap.uploadFiles,
				filePath: '', // 存放选择的文件路径
				fileName: '', // 存放选择的文件名
				fileIconUrl: '', // 存放选择的文件图标 URL
				publishForm: {
					title: '',
					intro: '',
					detail: '',
					keywords: '',
					price: '',
					city: '',
					imgList: [],
					state: 1,
				},
				projectid: null,
				finalKeywords: '',
				keywordsInput: '',
				readOnly: false, //是否只读
				photoUrl: 'https://kehu.ruoyiweb.hellomky.cn/', //服务器图片域名或者ip
				api: 'api/common/upload', //上传图片接口地址
				txt: '',
				name: 'file',
				values: '',
				form: {
					desc: '',
				},
				inputValue: '',
				intro: '',
				detail: '',
				imgList: []
			};
		},
		components: {
			piaoyiEditor,
			Attachment
		},
		onLoad(query) {
			let token = JSON.parse(uni.getStorageSync('vuexvuex'))
			var parsedData = JSON.parse(token.value);
			var tokenValue = parsedData.userinfo.token;
			let domainPrefix = this.$myHttp.config.baseUrl;
			this.domainPrefix = domainPrefix.replace(/\/$/, '');
			this.header['token'] = tokenValue;
			// 从 query 中获取传递的参数
			this.projectid = query.id || '';

			this.getCurrentProject()

		},
		methods: {
			async getCurrentProject() {
				let res = await this.$myHttp.post({
					url: this.$myHttp.urlMap.projectDetail,
					data: {
						id: this.projectid
					}
				})


				// 将新数据添加到项目列表中
				this.projectList = res.data.detail
				this.publishForm.title = this.projectList.name
				this.values = this.projectList.content
				this.keywordsInput = this.projectList.keywords
				this.publishForm.price = this.projectList.price
				this.publishForm.city = this.projectList.city


				if (this.projectList.attachfile !== '') {
					let domainPrefix = this.$myHttp.config.baseUrl;
					domainPrefix = domainPrefix.replace(/\/$/, '');
					let filesArray = this.projectList.attachfile.split(',');
					filesArray.forEach((file) => {
						// 对每个文件路径进行处理，创建一个对象并添加到 attachmentList 中
						let fileInfo = {
							url: `${domainPrefix + file}`, // 如果需要去掉引号，可以使用 file.replace(/"/g, '')
							type: 'file',
							fileName: file.split('/').pop() // 获取文件名
						};

						this.attachmentList.push(fileInfo);
					});
				}
				if (this.projectList.images !== '') {
					let domainPrefix = this.$myHttp.config.baseUrl;
					domainPrefix = domainPrefix.replace(/\/$/, '');
					let imagesArray = this.projectList.images.split(',');
					imagesArray.forEach((image) => {
						// 对每个文件路径进行处理，创建一个对象并添加到 attachmentList 中
						let imageInfo = {
							url: `${domainPrefix + image}`, // 如果需要去掉引号，可以使用 file.replace(/"/g, '')
							type: 'image',
							fileName: image.split('/').pop() // 获取文件名
						};

						this.attachmentList.push(imageInfo);
					});
				}
				





			},
			SwitchA(e) {
				this.switchA = e.detail.value
			},
			uploadSuccess(result) {
				const fileUrl = JSON.parse(result.data)
				console.log('fileUrl: ', fileUrl)

				// 获取文件扩展名
				const fileExtension = fileUrl.data.url.split(".").pop().toLowerCase();
				
				// 获取域名
				let domainPrefix = this.$myHttp.config.baseUrl;
				domainPrefix = domainPrefix.replace(/\/$/, '');

				// 根据扩展名判断文件类型
				if (fileExtension === "jpg" || fileExtension === "jpeg" || fileExtension === "png" || fileExtension ===
					"gif") {

					// 上传版本
					// // 将图片 URL 存放到图片变量中
					// if (this.ImagesList.length > 1) {
					// 	// 如果 this.ImagesList 不为空，则添加逗号
					// 	this.ImagesList += ',';
					// }

					// this.ImagesList += fileUrl.data.url;

					// let domainPrefix = this.$myHttp.config.baseUrl;
					// domainPrefix = domainPrefix.replace(/\/$/, '');
					// let imagesArray = this.projectList.images.split(',');

					// imagesArray.forEach((image) => {
					// 对每个文件路径进行处理，创建一个对象并添加到 attachmentList 中
					console.log('321321 ')
					let imageInfo = {
						url: `${domainPrefix + fileUrl.data.url}`, // 如果需要去掉引号，可以使用 file.replace(/"/g, '')
						type: 'image',
						fileName: fileUrl.data.url.split('/').pop() // 获取文件名
					};

					this.attachmentList.push(imageInfo);
					
					// });
					// this.attachmentList2.push(imageInfo);

				} else {
					// if (this.filesList.length > 1) {
					// 	this.filesList += ',';
					// }

					// this.filesList += fileUrl.data.url;

					let fileInfo = {
						url: `${domainPrefix + fileUrl.data.url}`, // 如果需要去掉引号，可以使用 file.replace(/"/g, '')
						type: 'file',
						fileName: fileUrl.data.url.split('/').pop() // 获取文件名
					};

					this.attachmentList.push(fileInfo);
					


				}
				if (result.statusCode == 200) {
					//上传成功的回调处理
					uni.showToast({
						title: '上传成功',
						icon: 'none'
					});
				} else {
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					});
				}
			},
			async publishBtn() {

				if (this.publishForm.title == '') {
					uni.showToast({
						title: '请填写项目名称！',
						icon: 'none'
					});

				} else if (this.publishForm.price == '') {
					uni.showToast({
						title: '请填写项目价格！',
						icon: 'none'
					});
				} else {
					let domainPrefix = this.$myHttp.config.baseUrl;
					domainPrefix = domainPrefix.replace(/\/$/, '');
					// domainPrefix = 'https://kehu.ruoyiweb.hellomky.cn';
					console.log('domainPrefix: ', domainPrefix)
					
					// 使用 map 方法将 url 属性组成一个字符串，并去掉 domainPrefix
					const imageUrlsString = this.attachmentList
						.filter(item => item.type === 'image') // 筛选出 type 为 "image" 的元素
						.map(item => item.url.replace(domainPrefix, '')) // 替换 domainPrefix 为空字符串
						.join(',');

					const filesString = this.attachmentList
						.filter(item => item.type === 'file') // 筛选出 type 为 "file" 的元素
						.map(item => item.url.replace(domainPrefix, '')) // 替换 domainPrefix 为空字符串
						.join(',');
					
					console.log('imageUrlsString: ', imageUrlsString)
					console.log('filesString: ', filesString)


					// 判断有无修改项目详情
					if (this.txt == '') {
						this.txt = this.values
					}

					// 如果没有添加也没有删除原本项目的附件，则重新提交原本的数据
					// if (this.projectList.images) {
					// 	if(this.ImagesList.length >0 ){
					// 		this.ImagesList += ','
					// 	}
					// 	this.ImagesList += this.projectList.images
					// 	console.log('this.ImagesList: ', this.ImagesList)
					// }
					// if (this.projectList.attachfile) {
					// 	if(this.filesList.length > 0 ){
					// 		this.ImagesList += ','
					// 	}
					// 	this.filesList += this.projectList.attachfile
					// 	console.log('this.filesList: ', this.filesList)
					// }

					console.log('AFTERthis.attachmentList', this.attachmentList)
					//

					// 如果项目详情没有动过，那么就重新把传过来的content
					// if (this.projectList.content == this.keywordsInput){

					// }


					// if (this.keywordsInput !== '') {
					// 	this.finalKeywords = this.keywordsInput.join(",");
					// }

						let res = await this.$myHttp.post({
							url: this.$myHttp.urlMap.updataProject,
							data: {
								id: this.projectid,
								name: this.publishForm.title,
								
								// content: JSON.stringify(this.txt),
								content: encodeURIComponent(this.txt),
								price: this.publishForm.price,
								keywords: this.keywordsInput,
								city: this.publishForm.city,
								images: imageUrlsString,
								attachfile: filesString,
							}
						})

						if (res.code == 1) {
							uni.showToast({
								title: '修改成功',
								icon: 'success', // 图标，可选值：success/loading/none
								duration: 2000, // 提示框显示时间，单位为毫秒
								mask: true, // 是否显示透明蒙层，防止触摸穿透
								success: function() {
									// showToast 完成后执行跳转
									setTimeout(function() {
										uni.navigateTo({
											url: '/subpackage/myProjects/myProjects', // 替换成你的目标页面路径
										});
									}, 1000);
								},
							});

						}
					}

				},
				// handleInput() {
				// 	// 将输入框中的字符串按逗号分隔
				// 	this.publishForm.keywords = this.keywordsInput.split(',');


				// },

				DelImg(e) {
						uni.showModal({
							title: '提示',
							content: '确定要删除这张图片吗？',
							cancelText: '取消',
							confirmText: '确定',
							success: res => {
								if (res.confirm) {
									this.imgList.splice(e.currentTarget.dataset.index, 1)
								}
							}
						})
					},

					//监听富文本内容改变
					editorChange(e) {
						this.form.desc = e
					},
					saveContens(e) {

						this.txt = e.html
					},
					ViewImage(e) {
						uni.previewImage({
							urls: this.imgList,
							current: e.currentTarget.dataset.url
						});
					},
					ChooseImage() {
						uni.chooseImage({
							count: 4, //默认9
							sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有

							sourceType: ['album'], //从相册选择
							success: (res) => {

								if (this.imgList.length != 0) {
									this.imgList = this.imgList.concat(res.tempFilePaths)

								} else {
									this.imgList = res.tempFilePaths

								}
							}
						});
					},
			}
		}
</script>

<style lang="scss" scoped>
	.uploadFile-container {
		display: flex;
		align-items: flex-start;
	}

	.writeInfo-contaienr {
		background-color: #fff;
		padding: 0rpx 40rpx;

		.publish-btn {
			display: flex;
			margin-top: 20rpx;
			padding-bottom: 20rpx;
			width: 100%;
			align-items: center;
			justify-content: center;
		}

		.price {
			display: flex;
			align-items: center;
			justify-content: space-between;

			.price-title {
				text-align: left;
				text-indent: 20rpx;
				font-size: 30rpx;
				color: #333333;
			}

			.price-body {
				display: flex;
				align-items: center;
				height: 100rpx;
				border-bottom: 1px solid #F4F4F4;
				text-align: left;
				text-indent: 20rpx;
				font-size: 30rpx;
				color: #333333;

				.danwei {
					font-size: 30rpx;
					color: #333333;
					height: 100%;

				}

				.price-input {
					height: 100%;
					border: none;
					outline: none;
					font-size: 30rpx;
					color: #333333;
				}
			}
		}

		.writeDetail-body {
			display: flex;
			align-items: flex-start;
			border-bottom: 1px solid #F4F4F4;

			.writeDetail {
				width: 100%;
				height: 100%;
				padding: 20rpx;
				border-bottom: 1px solid #F4F4F4;
				outline: none;
			}
		}

		.writeIntro-body {
			display: flex;
			align-items: flex-start;

			.writeIntro {
				width: 100%;
				height: 100%;
				padding: 20rpx;
				border-bottom: 1px solid #F4F4F4;
				outline: none;
			}
		}

		.wreteInfo-body {
			display: flex;
			align-items: flex-start;

			.wreteInfo {
				width: 100%;
				height: 100%;
				padding: 20rpx;
				border-bottom: 1px solid #F4F4F4;
				outline: none;
			}
		}

	}

	.spliceLine {
		width: 100%;
		height: 6px;
		background-color: #EFEFEF;
	}
</style>